<?php
  // no direct access
  defined( '_JEXEC' ) or die( 'Restricted access' );
  jimport('joomla.application.component.controller');
  include('base.php');

  class PlayerGameStatController extends BaseController
  {
    var $_name = 'playergamestat';

    function display()
    {
      $document =& JFactory::getDocument();

      $view = & $this->getView($this->_name, $document->getType());
      $view->setModel($this->getModel($this->_name), true);
      $view->setModel($this->getModel('season','seasonmodel'));

      $view->displayList();
    }

    function add()
    {
      $document =& JFactory::getDocument();

      $view = & $this->getView($this->_name, $document->getType());
      $view->setModel($this->getModel($this->_name), true);
      $view->setModel($this->getModel('team','teammodel'));
      $view->setModel($this->getModel('schedule','schedulemodel'));

      $view->displayAdd();
    }

    function edit()
    {
      $cids = JRequest::getVar('cid', null, 'default', 'array' );
      if($cids === null)
          JError::raiseError(500, 'cid parameter missing from the request');

      $document =& JFactory::getDocument();

      $view = & $this->getView($this->_name, $document->getType());
      $view->setModel($this->getModel($this->_name), true);
      $view->setModel($this->getModel('team','teammodel'));
      $view->setModel($this->getModel('schedule','schedulemodel'));
      $view->setModel($this->getModel('player','playermodel'));
      $view->setModel($this->getModel('person','personmodel'));

      $view->displayEdit();
    }

    function export(){
      $season_id = JRequest::getVar('season_id');
      $weeks     = JRequest::getVar('weeks');

      $season = $this->getModel('season', 'seasonmodel');
      $season = $season->get($season_id);

      # gather scheds (date start and ends)
      $s_weeks = $this->get_weeks($season);
      $scheds = array();
      foreach(array_values($weeks) as $id)
        array_push($scheds, $s_weeks[($id-1)]);

      # get db schedules
      $schedule  = $this->getModel('schedule', 'schedulemodel');
      $db_scheds = array();
      foreach($scheds as $sched){
        $temp = array_values($schedule->get_by_schedule($sched->start, $sched->end));
        $db_scheds = array_merge($db_scheds, $temp);
      }

      # get teams and players
      $teams = $this->get_teams_and_players();

      # export to excel
      $this->export_to_excel($db_scheds, $teams);
      die();
    }

    function import(){
      $data = JRequest::getVar('file_upload',null,'files');
	  if(!empty($data)){

        $file = $data['tmp_name'];
        $fh   = fopen($file, 'r');

        $schedule_id = null;
        $team_id     = null;

        while(!feof($fh)){
          $line = fgets($fh);
          $row  = explode(',', $line);

          if(!empty($row) && isset($row[1])){
            switch($row[1]){

              case 'SCHEDULE:':
                $schedule_id = $row[0];
                break;

              case 'PLAYER:':
                $player_id = $row[0];
                $this->create_playergamestat($schedule_id, $player_id, $row);
                break;
            }
          }

        }

        # move file
        $destination = JPATH_COMPONENT_ADMINISTRATOR.DS.'uploads'.DS."Importing_".time();
        copy($file, $destination); # not working, copy file for backup purposes
      }

      $this->display();
    }

    function ajx_select_players()
    {
      $team_id = JRequest::getVar('team_id');

      $person = $this->getModel('person','personmodel');
      $player = $this->getModel('player','playermodel');

      $players = $player->get_by_team_id($team_id);

	  if(!empty($players)){
        for($i=0;$i<count($players);$i++){

          $p   = $players[$i];
          $tmp = $person->get($p->person_id);
          $p->name = $tmp->lastname.", ".$tmp->firstname;

        }
      }
	  else
	    $players = array();

      $result  = JHTML::_('select.genericlist', $players, 'player_id', null, 'id', 'name', null);
      echo $result;
    }

    function ajx_get_weeks()
    {

      $team_id = JRequest::getVar('season_id');
      $season  = $this->getModel('season','seasonmodel');
      $temp_r  = $this->get_weeks($season->get_latest());
      $result  = array();

      foreach($temp_r as $index => $week){
        $obj = new stdClass;
        $obj->id   = $index;

        $start = $week->start;
        $end   = $week->end;

        $obj->name = "Wk " . ($index+1) . " : $start - $end";
        array_push($result, $obj);
      }
      $result  = JHTML::_('select.genericlist', $result, 'weeks[]', 'multiple=multiple size=10', 'id', 'name', null);
      echo $result;
    }

    /* returns the weeks within the season indexed from 0.... */
    private function get_weeks($season){

      $result = array();
      if(!$season)
        return $result;

      $start  = strtotime($season->start_date);
      $end    = strtotime($season->end_date);
      $sec_wk = 60*60*24*7;
      $weeks  = floor(($end - $start)/$sec_wk);

      for($i = 0; $i < $weeks; $i++){
        $result[$i] = new stdClass();
        $result[$i]->start = strftime('%Y-%m-%d', $start + ($i * $sec_wk));
        $result[$i]->end   = strftime('%Y-%m-%d', $start + (($i + 1) * $sec_wk));
      }

      return $result;
    }

    private function get_teams_and_players(){

      $m_team   = $this->getModel('team', 'teammodel');
      $m_player = $this->getModel('player', 'playermodel');
      $m_person = $this->getModel('person', 'personmodel');

      $results  = array();

      foreach($m_team->get() as $team){

        # get players
        $players = $m_player->get_by_team_id($team->id);

        # get names
		if($players){
          foreach($players as $player)
            $player->name = $m_person->get_fullname($player->person_id);

          # add players to team
          $team->players = $players;
          $results[$team->id] = $team;
		}
      }
      return $results;

    }

    private function export_to_excel($scheds, $teams){

      # create excel
      header("Content-type: text/csv");
      header("Cache-Control: no-store, no-cache");
      header("Content-Disposition: attachment; filename=\"Encoding.csv\"");

      $fh = fopen("php://output",'w');

      # HEADER
      fputcsv($fh, array('ID','TYPE','JERSEY','NAME','PTS',
                         'FG', 'FGA',
                         'TP', 'TPA',
                         'FT', 'FTA',
                         'O\'REB', 'D\'REB',
                         'A', 'S', 'B'));

      # BODY
      foreach($scheds as $sched){

        fputcsv($fh, array());# spacer row
        fputcsv($fh, array());# spacer row

        $row = array($sched->id, 'SCHEDULE:', '',  $sched->notes.'-'.$sched->schedule);
        fputcsv($fh, $row);

        # team 1
        $row = array($sched->first_team_id, 'TEAM:', $teams[$sched->first_team_id]->name);
        fputcsv($fh, $row);

        # players for team 1
        foreach($teams[$sched->first_team_id]->players as $player){
          $row = array($player->id, 'PLAYER:', $player->jersey_number, $player->name);
          fputcsv($fh, $row);
        }

        # team 2
        $row = array($sched->second_team_id, 'TEAM:',  $teams[$sched->second_team_id]->name);
        fputcsv($fh, $row);

        # players for team 1
        foreach($teams[$sched->second_team_id]->players as $player){
          $row = array($player->id, 'PLAYER:', $player->jersey_number, $player->name);
          fputcsv($fh, $row);
        }

      }
      fclose($fh);
    }

    private function create_playergamestat($schedule_id, $player_id, $row){

      $columns = array("PTS" => 5,
                       "FG"  => 6,
                       "FGA" => 7,
                       "TP"  => 8,
                       "TPA" => 9,
                       "FT"  => 10,
                       "FTA" => 11,
                       "OREB" => 12,
                       "DREB" => 13,
                       "A"   => 14,
                       "S"   => 15,
                       "B"   => 16);

      $m_pgs = $this->getModel('playergamestat', 'playergamestatmodel');

      if(in_array(null, array($schedule_id, $player_id)))
        throw new Exception('parameters should not be null');

      $params = array();
	  $params['points']               = $row[$columns["PTS"]];
	  $params['field_goals']          = $row[$columns["FG"]];
	  $params['field_goal_attempts']  = $row[$columns["FGA"]];
	  $params['three_points']         = $row[$columns["TP"]];
	  $params['three_point_attempts'] = $row[$columns["TPA"]];
	  $params['free_throws']          = $row[$columns["FT"]];
	  $params['free_throw_attempts']  = $row[$columns["FTA"]];
	  $params['off_rebounds']         = $row[$columns["OREB"]];
	  $params['def_rebounds']         = $row[$columns["DREB"]];
	  $params['assists']              = $row[$columns["A"]];
	  $params['steals']               = $row[$columns["S"]];
	  $params['blocks']               = $row[$columns["B"]];
	  $params['schedule_id']          = $schedule_id;
	  $params['player_id']            = $player_id;
	  $params['published']            = true;
	  
	  if(in_array(null, array_values($params)))
	    throw new Exception("incomplete playergamestats parameters: $row[3], $row[4]");
	  
      $pgs    = $m_pgs->get_by($schedule_id, $player_id);
      if($pgs)
        $params['id'] = $pgs->id;
      
	  $m_pgs->save($params);
	}

  }
?>
